import { createRouter, createWebHashHistory } from 'vue-router';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () =>
      import(/* webpackChunkName:'home' */ '../views/home/Home.vue'),
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: () =>
      import(/* webpackChunkName:'shop' */ '../views/shop/Shop.vue'),
  },
  {
    path: '/register',
    name: 'Register',
    component: () =>
      import(
        /* webpackChunkName:'register' */ '../views/register/Register.vue'
      ),
    beforeEnter: (to, from, next) => {
      const { isLogin } = localStorage;
      isLogin ? next({ name: 'Home' }) : next();
    },
  },
  {
    path: '/login',
    name: 'Login',
    component: () =>
      import(/* webpackChunkName:'login' */ '../views/login/Login.vue'),
    beforeEnter: (to, from, next) => {
      const { isLogin } = localStorage;
      isLogin ? next({ name: 'Home' }) : next();
      // console.log(to, from);
    },
  },
  {
    path: '/cartList',
    name: 'CartList',
    component: () =>
      import(
        /* webpackChunkName:'cartList' */ '../views/cartList/CartList.vue'
      ),
  },
  {
    path: '/orderConfirm/:id',
    name: 'OrderConfirm',
    component: () =>
      import(
        /* webpackChunkName:'orderConfirm' */ '../views/orderConfirm/OrderConfirm.vue'
      ),
  },
  {
    path: '/orderList',
    name: 'OrderList',
    component: () =>
      import(
        /* webpackChunkName:'orderList' */ '../views/orderList/OrderList.vue'
      ),
  },
  {
    path: '/search',
    name: 'Search',
    component: () =>
      import(/* webpackChunkName:'search' */ '../views/search/Search.vue'),
  },
  {
    path: '/searchList',
    name: 'SearchList',
    component: () =>
      import(
        /* webpackChunkName:'searchList' */ '../views/searchList/SearchList.vue'
      ),
  },
  {
    path: '/myAddressList',
    name: 'MyAddressList',
    component: () =>
      import(
        /* webpackChunkName:'address' */ '../views/myAddressList/MyAddressList.vue'
      ),
  },
  {
    path: '/personalInfo',
    name: 'PersonalInfo',
    component: () =>
      import(
        /* webpackChunkName:'personInfo' */ '../views/personalInfo/PersonalInfo.vue'
      ),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const { isLogin } = localStorage;

  const { name } = to;
  const isLoginOrRegister = name === 'Login' || name === 'Register';

  isLogin || isLoginOrRegister ? next() : next({ name: 'Login' });

  // console.log(to, from);
});

export default router;
